package com.lu.manage.modular.system.service.impl;

import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lu.manage.core.common.constant.SystemConstant;
import com.lu.manage.core.common.node.TreeNodes;
import com.lu.manage.core.common.node.ZTreeNode;
import com.lu.manage.core.tips.SuccessTip;
import com.lu.manage.core.utils.ToolUtil;
import com.lu.manage.modular.system.mapper.RoleMapper;
import com.lu.manage.modular.system.model.MenuRoleRelation;
import com.lu.manage.modular.system.model.Role;
import com.lu.manage.modular.system.service.MenuRoleService;
import com.lu.manage.modular.system.service.RoleService;
import com.lu.manage.modular.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * @program LuBoot
 * @description:
 * @author: zhanglu
 * @create: 2019-10-08 10:30:00
 */
@Transactional(rollbackFor = Exception.class)
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private UserService userService;

    @Autowired
    private MenuRoleService menuRoleService;

    @Override
    public Role add(Role role) throws Exception {
        this.save(role);
        return role;
    }

    @Override
    public void update(Role role) throws Exception {
        this.updateById(role);
    }

    @Override
    public void delete(String roleId) throws Exception {

        //删除角色
        this.baseMapper.deleteById(roleId);

        //删除角色所有的权限
        this.baseMapper.deleteRolesById(roleId);
    }

    @Override
    public void sortAllRoles(String nodes) throws Exception {
        List<TreeNodes> nodesList = JSONArray.parseArray(nodes, TreeNodes.class);
        System.out.println(nodes);
        for (TreeNodes node : nodesList) {
            handle( node);
        }
        sortIndex = 0;
    }

    public static int sortIndex = 0;

    public void handle(TreeNodes treeNodes){
        for (TreeNodes n : treeNodes.getChildren()) {
            if(ToolUtil.isNotEmpty(n.getId()) && !n.getId().equals(SystemConstant.pid)){
                if(ToolUtil.isEmpty(n.getChildren())){
                    Role role = new Role();
                    role.setRoleId(n.getId());
                    role.setSort(sortIndex);
                    sortIndex++;
                    this.baseMapper.updateById(role);
                }else {
                    Role role = new Role();
                    role.setRoleId(n.getId());
                    role.setSort(sortIndex);
                    sortIndex++;
                    this.baseMapper.updateById(role);
                    handle(n);
                }
            }
        }
    }

    @Override
    public Object listPage(Map<String, Object> map) {

        SuccessTip successTip = new SuccessTip();

        try {
            Page page = new Page(Integer.valueOf((String)map.get(SystemConstant.PAGE)), Integer.valueOf((String)map.get(SystemConstant.LIMIT)));
            IPage<Role> pageList = this.baseMapper.listPage(page, map);

            successTip.setCount(pageList.getTotal());
            successTip.setData(pageList.getRecords());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return successTip;
    }

    @Override
    public Object roleTreeList() {
        return this.baseMapper.roleTreeList();
    }

    @Override
    public void setAuthority(String roleId, String ids) throws Exception {

        //删除该角色所有的权限
        this.baseMapper.deleteRolesById(roleId);

        // 添加新的权限
        for (String id : Convert.toStrArray(ids.split(","))) {
            MenuRoleRelation relation = new MenuRoleRelation();
            relation.setRoleId(roleId);
            relation.setMenuId(id);
            menuRoleService.save(relation);
        }

        // 刷新当前用户的权限
        userService.refreshCurrentUser();

    }

    @Override
    public List<ZTreeNode> roleTreeListByRoleId(String[] strArray) {
        return this.baseMapper.roleTreeListByRoleId(strArray);
    }
}
